package com.member.web.controller.shop;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.member.common.annotation.Anonymous;
import com.member.common.annotation.Log;
import com.member.common.core.domain.AjaxResult;
import com.member.common.enums.BizUserStatusEnum;
import com.member.common.enums.BusinessType;
import com.member.common.enums.OrderDeleteEnum;
import com.member.common.enums.ProcessStatusEnum;
import com.member.common.utils.DateUtils;
import com.member.common.utils.SecurityUtils;
import com.member.common.utils.StringUtils;
import com.member.common.utils.TokenUtils;
import com.member.common.utils.bean.BeanUtils;
import com.member.common.utils.poi.ExcelUtil;
import com.member.shop.domain.*;
import com.member.shop.dto.*;
import com.member.shop.mapper.SysBizRegionMapper;
import com.member.shop.service.*;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/*sz 用户同步*/
@Anonymous
@RestController
@RequestMapping("/shop/sz")
public class SzUserExternal {


    @Resource
    private ISysBizUserService sysBizUserService;

    @Resource
    private ISysBizUserAddressService sysBizUserAddressService;


    @Resource
    private ISysBizShopCertificationService sysBizShopCertificationService;


    @Resource
    private SysBizRegionMapper sysBizRegionMapper;


    /**
     * 商品库存变动接口
     */
    @Log(title = "商品模板", businessType = BusinessType.INSERT)
    @PostMapping("/userImport")
    public AjaxResult  batchImport(MultipartFile file,HttpServletResponse response) throws Exception {
        ExcelUtil<SzUserImportDto> util = new ExcelUtil<>(SzUserImportDto.class);
        List<SzUserImportDto> batchImporList = util.importExcel(file.getInputStream());
        if (CollectionUtils.isEmpty(batchImporList)) {
            return AjaxResult.error("列表不能为空");
        }
        for (SzUserImportDto szUserImportDto : batchImporList) {

            String name = szUserImportDto.getShopName();
            String phone = szUserImportDto.getPhone();

            if(StringUtils.isBlank(phone)){
                continue;
            }

            SysBizUser bizUser = sysBizUserService.getOne(new LambdaQueryWrapper<SysBizUser>()
                    .eq(SysBizUser::getUserPhone, phone)
                    .eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));

            SysBizUser sysBizUser = new SysBizUser();
            if(bizUser == null){
                sysBizUser.setUserPhone(phone);
                sysBizUser.setPassword(SecurityUtils.encryptPassword(phone));
                sysBizUser.setNickName(StringUtils.isBlank(name)?"禾饴"+ RandomStringUtils.randomAlphabetic(8):name);
                sysBizUser.setIsRegisterMember(0);
                sysBizUser.setDisplayed(BizUserStatusEnum.OK.getKey());
                sysBizUser.setCreateTime(DateUtils.getNowDate());
                sysBizUser.setTenantId(3L);
                sysBizUser.setScore(0L);
                sysBizUser.setGrade(0L);
                sysBizUser.setIsAdmin(0);
                sysBizUser.setUserRole(1);
                sysBizUser.setUpdateTime(new Date());
                sysBizUser.setDeleted(0);
                sysBizUser.setUseScore(0L);
                sysBizUser.setFrozenScore(0L);
                String token = TokenUtils.createToken();
                sysBizUser.setToken(token);
                sysBizUser.setProcessStatus(ProcessStatusEnum.UN_PROCESS.getKey());
                sysBizUser.setAuthenticationStatus(0);
                sysBizUserService.save(sysBizUser);
            }else{
                sysBizUser.setTenantId(bizUser.getTenantId());
                sysBizUser.setId(bizUser.getId());
            }


            SysBizUserAddress sysBizAddress = new SysBizUserAddress();
            sysBizAddress.setTenantId(sysBizUser.getTenantId());
            sysBizAddress.setUserId(sysBizUser.getId());
            sysBizAddress.setPhone(phone);
            sysBizAddress.setProvince("江苏省"); //省
            sysBizAddress.setCity("苏州市"); //市
            sysBizAddress.setArea(szUserImportDto.getArea());

            sysBizAddress.setName(szUserImportDto.getContacts());      //收件人
            sysBizAddress.setDetails(szUserImportDto.getAddress());
            sysBizAddress.setStatus(0);
            sysBizAddress.setCreateTime(DateUtils.getNowDate());
            sysBizAddress.setUpdateTime(DateUtils.getNowDate());
            sysBizAddress.setStreet(szUserImportDto.getStreet());
//            sysBizAddress.setHouseNum(szUserImportDto.getAddress());   //门牌号

            List<SysBizRegion> sysBizRegions = sysBizRegionMapper.selectList(new LambdaQueryWrapper<SysBizRegion>()
                    .eq(SysBizRegion::getTitle, szUserImportDto.getStreet()));

            sysBizAddress.setProvinceCode("320000");
            sysBizAddress.setCityCode("320500");
            if(!CollectionUtils.isEmpty(sysBizRegions)){
                sysBizAddress.setAreaCode(sysBizRegions.get(0).getFathercode());
                sysBizAddress.setStreetCode(sysBizRegions.get(0).getCode());  // 街道编号
            }
            sysBizUserAddressService.save(sysBizAddress);


            SysBizShopCertification sysBizShopCertification = new SysBizShopCertification();
            sysBizShopCertification.setUserId(sysBizUser.getId());
            sysBizShopCertification.setTenantId(sysBizUser.getTenantId());
            sysBizShopCertification.setShopName(szUserImportDto.getShopName());
            sysBizShopCertification.setShopType(szUserImportDto.getShopName());   //店铺类型
            sysBizShopCertification.setCertificationStatus(3);
            sysBizShopCertification.setApplyTime(LocalDateTime.now());
            sysBizShopCertification.setAuditTime(LocalDateTime.now());
            sysBizShopCertification.setContacts(szUserImportDto.getContacts());   //联系人
            sysBizShopCertification.setProvince("江苏省");
            sysBizShopCertification.setCity("苏州市");
            sysBizShopCertification.setArea(szUserImportDto.getArea());
            sysBizShopCertification.setAddress(szUserImportDto.getAddress());
            sysBizShopCertificationService.save(sysBizShopCertification);
        }
        return AjaxResult.success();

    }
//
//    @Resource
//    private ISysBizShopCategoryService sysBizShopCategoryService;
//
//    /**
//     * copy category
//     */
//    @GetMapping("/copyCategory")
//    @Transactional(rollbackFor = Exception.class)
//    public AjaxResult copyCategory() throws Exception {
//        List<SysBizShopCategory> rootCategories = sysBizShopCategoryService.selectSysBizShopCategoryList(
//                new LambdaQueryWrapper<SysBizShopCategory>()
//                        .eq(SysBizShopCategory::getParentId, 0)
//                        .eq(SysBizShopCategory::getTenantId, 1)
//                        .eq(SysBizShopCategory::getDeleted, 0));
//
//        if (CollectionUtils.isEmpty(rootCategories)) {
//            return AjaxResult.success(Collections.emptyList());
//        }
//
//        for (SysBizShopCategory root : rootCategories) {
//            // 复制一级分类
//            SysBizShopCategory newRoot = new SysBizShopCategory();
//            BeanUtils.copyProperties(root,newRoot);
//            newRoot.setId(null);         // 清除主键以生成新记录
//            newRoot.setTenantId(2L);     // 修改租户
//            sysBizShopCategoryService.save(newRoot);
//
//            // 查询子分类
//            List<SysBizShopCategory> children = sysBizShopCategoryService.selectSysBizShopCategoryList(
//                    new LambdaQueryWrapper<SysBizShopCategory>()
//                            .eq(SysBizShopCategory::getParentId, root.getId())
//                            .eq(SysBizShopCategory::getDeleted, 0));
//
//            List<SysBizShopCategory> newChildren = new ArrayList<>();
//            for (SysBizShopCategory child : children) {
//                SysBizShopCategory newChild = new SysBizShopCategory();
//                BeanUtils.copyProperties(child,newChild);
//                newChild.setId(null);             // 新建记录
//                newChild.setTenantId(2L);         // 修改租户
//                newChild.setParentId(newRoot.getId()); // 指向新父类
//                newChildren.add(newChild);
//            }
//
//            if (!CollectionUtils.isEmpty(newChildren)) {
//                sysBizShopCategoryService.saveBatch(newChildren);
//            }
//        }
//
//        return AjaxResult.success("分类复制成功");
//    }
//
//    @Resource
//    private ISysBizShopSpecsService sysBizShopSpecsService;
//
//    /**
//     * copySpecs
//     */
//    @GetMapping("/copySpecs")
//    @Transactional(rollbackFor = Exception.class)
//    public AjaxResult copySpecs() throws Exception {
//        List<SysBizShopSpecs> rootCategories = sysBizShopSpecsService.selectSysBizShopSpecsList(
//                new LambdaQueryWrapper<SysBizShopSpecs>()
//                        .eq(SysBizShopSpecs::getParentId, 0)
//                        .eq(SysBizShopSpecs::getDeleted, 0));
//
//        if (CollectionUtils.isEmpty(rootCategories)) {
//            return AjaxResult.success(Collections.emptyList());
//        }
//
//        for (SysBizShopSpecs root : rootCategories) {
//            // 复制一级分类
//            SysBizShopSpecs newRoot = new SysBizShopSpecs();
//            BeanUtils.copyProperties(root,newRoot);
//            newRoot.setId(null);         // 清除主键以生成新记录
//            newRoot.setTenantId(3L);     // 修改租户
//            sysBizShopSpecsService.save(newRoot);
//
//            // 查询子分类
//            List<SysBizShopSpecs> children = sysBizShopSpecsService.selectSysBizShopSpecsList(
//                    new LambdaQueryWrapper<SysBizShopSpecs>()
//                            .eq(SysBizShopSpecs::getParentId, root.getId())
//                            .eq(SysBizShopSpecs::getDeleted, 0));
//
//            List<SysBizShopSpecs> newChildren = new ArrayList<>();
//            for (SysBizShopSpecs child : children) {
//                SysBizShopSpecs newChild = new SysBizShopSpecs();
//                BeanUtils.copyProperties(child,newChild);
//                newChild.setId(null);             // 新建记录
//                newChild.setTenantId(3L);         // 修改租户
//                newChild.setParentId(newRoot.getId()); // 指向新父类
//                newChildren.add(newChild);
//            }
//
//            if (!CollectionUtils.isEmpty(newChildren)) {
//                sysBizShopSpecsService.saveBatch(newChildren);
//            }
//        }
//
//        return AjaxResult.success("分类复制成功");
//    }

}
